package org.jeecg.modules.basic.iouser.service.impl;


import net.sf.json.JSONObject;
import org.jeecg.modules.basic.entry.util.*;
import org.jeecg.modules.basic.iouser.entity.LwgyInoutUser;
import org.jeecg.modules.basic.iouser.mapper.LwgyInoutUserMapper;
import org.jeecg.modules.basic.iouser.service.ILwgyInoutUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.jeecg.modules.basic.entry.util.HttpRequestToPrivate.sendPost;
import static org.jeecg.modules.basic.entry.util.StringUtil.getBytes;
import static org.jeecg.modules.basic.entry.util.StringUtil.getMD5;


/**
 * @Description: 人员信息采集
 * @Author: jeecg-boot
 * @Date:   2021-03-19
 * @Version: V1.0
 */
@Service
public class LwgyInoutUserServiceImpl extends ServiceImpl<LwgyInoutUserMapper, LwgyInoutUser> implements ILwgyInoutUserService {
    @Value("${jeecg.path.upload}")
    private String upLoadPath;
    @Autowired
    private LwgyInoutUserMapper lwgyInoutUserMapper;


//===================公有云接口
    //添加人员信息
    @Override
    public String saveIouserToPublic(LwgyInoutUser lwgyInoutUser) throws Exception {


        String url = SenseTimeEnumToPublic.HOST.getMsg() + SenseTimeEnumToPublic.SAVEUSER_URL.getMsg();        //表单文本参数
        Map<String, Object> params = new HashMap();

        String timestamp = String.valueOf(System.currentTimeMillis());
        //添加表单文本参数
        {
            params.put("name", lwgyInoutUser.getName());//人员姓名
            params.put("mobile",lwgyInoutUser.getMobile());//手机号
            params.put("remark",lwgyInoutUser.getRemark());//备注
            params.put("groups", lwgyInoutUser.getGroups());//人员组列表
            params.put("icNumber","");//IC卡号，可以为空串，长度限制45
            params.put("jobNumber",lwgyInoutUser.getJobNumber());//人员工号，可以为空串，长度限制45
            String sex = null;
            if( lwgyInoutUser.getGender().equals("1")){
                sex="2";
            }else if(lwgyInoutUser.getGender().equals("2")){
                sex="1";
            }
            params.put("gender", sex);//性别，1：女，2：男
           // params.put("gender", lwgyInoutUser.getGender());//性别，1：女，2：男
            params.put("force","1" );//强制添加
            params.put("app_key", SenseTimeEnumToPublic.APP_KEY.getMsg());
            params.put("timestamp", timestamp);
            params.put("sign", getMD5(timestamp + "#" + SenseTimeEnumToPublic.APP_SECRET.getMsg()));
        }
        String result;
        System.out.println("getAvatarfile:"+lwgyInoutUser.getAvatarFile());
        if(lwgyInoutUser.getAvatarFile() != null && !lwgyInoutUser.getAvatarFile().equals("")&& !lwgyInoutUser.getAvatarFile().equals("undefined")){
            //表单文件参数
            Map<String, byte[]> fileParams = new HashMap();

            String path=upLoadPath+ File.separator+ lwgyInoutUser.getAvatarFile();
            path = reformPath(path);

            File avatar_file = new File(path);
            String name = avatar_file.getName();
            //添加表单文件参数
            {
                fileParams.put("avatarFile", getBytes(avatar_file));
            }
             result = new String(HttpRequestToPublic.sendPost(url, params, fileParams,name));
        }else{
            result = new String(HttpRequestToPublic.sendPost(url, params, null,null));
        }

        System.out.println("========result========:"+result);
        return result;

    }
    //更新人员信息
    @Override
    public String updateIouserToPublic(LwgyInoutUser lwgyInoutUser) throws Exception {


        String url = SenseTimeEnumToPublic.HOST.getMsg() + SenseTimeEnumToPublic.UPDATEUSER_URL.getMsg()+"/"+lwgyInoutUser.getGuestId();        //表单文本参数
        Map<String, Object> params = new HashMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        //添加表单文本参数
        {
//            params.put("id", lwgyInoutUser.getGuestId());//修改人id
            params.put("groups", lwgyInoutUser.getGroups());//人员组需要需要改
            params.put("app_key", SenseTimeEnumToPublic.APP_KEY.getMsg());
            params.put("timestamp", timestamp);
            params.put("sign", getMD5(timestamp + "#" + SenseTimeEnumToPublic.APP_SECRET.getMsg()));
        }
        String result = new String(sendPost(url, params, null,null));
        System.out.println("========result========:"+result);
        return result;

    }
    //照片质量检测
    @Override
    public String qualityToPublic(String avatarFile) throws Exception {
        //D:/opt/upFiles\temp/WechatIMG1240_1628235247491.jpeg

        //本机要上传的图片位置
        String url = SenseTimeEnumToPublic.HOST.getMsg() + SenseTimeEnumToPublic.QUALITY_URL.getMsg();        //表单文本参数
        System.out.println("url:"+url);
        Map<String, Object> params = new HashMap();
        //表单文件参数
        Map<String, byte[]> fileParams = new HashMap();

        String path=upLoadPath+ File.separator+ avatarFile;
        path = reformPath(path);
        System.out.println("path:"+path);
        String timestamp = String.valueOf(System.currentTimeMillis());


        //添加表单文本参数
        {
            params.put("app_key", SenseTimeEnumToPublic.APP_KEY.getMsg());
            params.put("timestamp", timestamp);
            params.put("sign", getMD5(timestamp + "#" + SenseTimeEnumToPublic.APP_SECRET.getMsg()));
        }


        File avatar_file = new File(path);

        String name = avatar_file.getName();

        //添加表单文件参数
        {
            fileParams.put("face_avatar", getBytes(avatar_file));
        }
        String result = new String(HttpRequestToPublic.sendPost(url, params, fileParams,name));
        System.out.println("========result========:"+result);
        return result;
    }



    //================私有云接口
    //添加人员信息
    @Override
    public String saveIouserToPrivate(LwgyInoutUser lwgyInoutUser) throws Exception {


        String url = SenseTimeEnumToPrivate.HOST.getMsg() + SenseTimeEnumToPrivate.SAVEUSER_URL.getMsg();        //表单文本参数
        JSONObject params=new JSONObject();
        params.put("type", 1);
        params.put("name", lwgyInoutUser.getName());//人员姓名
        params.put("mobile",lwgyInoutUser.getMobile());//手机号
        params.put("remark",lwgyInoutUser.getRemark());//备注
        params.put("groups", lwgyInoutUser.getGroups());//人员组列表
        params.put("icNumber","");//IC卡号，可以为空串，长度限制45
        params.put("jobNumber",lwgyInoutUser.getJobNumber());//人员工号，可以为空串，长度限制45
        String sex = null;
        if( lwgyInoutUser.getGender().equals("1")){
            sex="2";
        }else if(lwgyInoutUser.getGender().equals("2")){
            sex="1";
        }
        params.put("gender", sex);//性别，1：女，2：男

        String result;
        if(lwgyInoutUser.getAvatarFile() != null && !lwgyInoutUser.getAvatarFile().equals("")&& !lwgyInoutUser.getAvatarFile().equals("undefined")){
            //表单文件参数
            String path=upLoadPath+ File.separator+ lwgyInoutUser.getAvatarFile();
            path = reformPath(path);

            params.put("avatarBytes", ImageUtil.getImageStr(path));
        }

        result = new String(HttpRequestToPrivate.sendPostByJSON(url, params.toString()));
        System.out.println("========result========:"+result);
        return result;

    }

    //更新人员信息
    @Override
    public String updateIouserToPrivate(LwgyInoutUser lwgyInoutUser) throws Exception {


        String url = SenseTimeEnumToPrivate.HOST.getMsg() + SenseTimeEnumToPrivate.UPDATEUSER_URL.getMsg()+"/"+lwgyInoutUser.getGuestId();        //表单文本参数
        Map<String, Object> params = new HashMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        //添加表单文本参数
        {
//            params.put("id", lwgyInoutUser.getGuestId());//修改人id
            params.put("groups", lwgyInoutUser.getGroups());//人员组需要需要改
            params.put("app_key", SenseTimeEnumToPrivate.APP_KEY.getMsg());
            params.put("timestamp", timestamp);
            params.put("sign", getMD5(timestamp + "#" + SenseTimeEnumToPrivate.APP_SECRET.getMsg()));
        }
        String result = new String(sendPost(url, params, null,null));
        System.out.println("========result========:"+result);
        return result;

    }
    //人像质量检测
    @Override
    public String qualityToPrivate(String avatarFile) throws Exception {
        //本机要上传的图片位置
        String url = SenseTimeEnumToPrivate.HOST.getMsg() + SenseTimeEnumToPrivate.QUALITY_URL.getMsg();        //表单文本参数
        JSONObject params=new JSONObject();
        String path=upLoadPath+ File.separator+ avatarFile;
        path = reformPath(path);

        params.put("faceAvatar", ImageUtil.getImageStr(path));
        String result = new String(HttpRequestToPrivate.sendPostByJSON(url, params.toString()));
        System.out.println("========result========:"+result);
        return result;
    }

    @Override
    public String addGroupsToPrivate(LwgyInoutUser lwgyInoutUser) throws Exception{

        String url = SenseTimeEnumToPrivate.HOST.getMsg() + SenseTimeEnumToPrivate.GROUP_URL.getMsg()
                +"/"+lwgyInoutUser.getGroups()+"/users";
        JSONObject params=new JSONObject();
        int a[] = new int[1];
        a[0]=Integer.parseInt(lwgyInoutUser.getGuestId());
        params.put("userIds",a);
        //添加表单文本参数
        String result = HttpRequestToPrivate.sendPostByJSON(url, params.toString());
        return result;
    }

    @Override
    public String updateGroupsToPrivate(LwgyInoutUser lwgyInoutUser) throws Exception{

        String url = SenseTimeEnumToPrivate.HOST.getMsg() + SenseTimeEnumToPrivate.UPDATE_USER_GROUP.getMsg()
                +"/"+lwgyInoutUser.getGuestId()+"/groups";
        JSONObject params=new JSONObject();
        int a[] = new int[1];
        a[0]=Integer.parseInt(lwgyInoutUser.getGroups());
        params.put("groupIds",a);
        //添加表单文本参数
        String result = HttpRequestToPrivate.sendPutByJSON(url, params.toString());
        return result;
    }

    @Override
    public LwgyInoutUser getUserByStudentId(String studentId){
        return lwgyInoutUserMapper.getUserByStudentId(studentId);
    }
    @Override
    public String getGroupIdByBuildingId(String building){
        return lwgyInoutUserMapper.getGroupIdByBuildingId(building);
    }

    //获取系统中没有userId的数据列表（未同步到商汤）
    public List<LwgyInoutUser> selectNoUserId(){
        return lwgyInoutUserMapper.selectNoUserId();
    }

    public List<Map<String, String>> getGroupData(String type){
        return lwgyInoutUserMapper.getGroupData(type);
    }

    public String reformPath(String path){
        if (path.contains("//")) {
            path = path.replace("//", "/");
        }
        if (path.contains("\'")) {
            path = path.replace("\'", "/");
        }
        return path;
    }


}

